package com.leigang.monitor.controller;

import com.leigang.common.parent.enums.ErrorEnums;
import com.leigang.common.parent.pojo.vo.ResponseVo;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author leig-a
 * @version 1.0
 * @desc  统一异常处理
 * @date 2023/3/8 15:09
 */
@Slf4j
@RestControllerAdvice
public class ExceptionController<T> {

    @ExceptionHandler(value = {
            MissingServletRequestParameterException.class,
            HttpMessageNotReadableException.class,
            MethodArgumentTypeMismatchException.class
    })
    public ResponseVo<T> notHandlerFoundExceptionHandler(Exception e){
        log.error("MissingServletRequestParameterException, HttpMessageNotReadableException, " +
                "MethodArgumentTypeMismatchException 发生异常:{}", e.getMessage(), e);
        return ResponseVo.error(ErrorEnums.FAILURE.getCode(), e.getMessage(), null);
    }

    @ExceptionHandler(value = {FeignException.class})
    public ResponseVo<T> exception(FeignException e) {
        log.error("FeignException 发生异常:{}", e.getMessage(), e);
        return ResponseVo.error(ErrorEnums.FAILURE.getCode(), e.getMessage(),null);
    }

    @ExceptionHandler(value = {SQLIntegrityConstraintViolationException.class})
    public ResponseVo<T> exception(SQLIntegrityConstraintViolationException e) {
        log.error("SQLIntegrityConstraintViolationException 发生异常:{}", e.getMessage(), e);
        return ResponseVo.error(ErrorEnums.FAILURE.getCode(), e.getMessage(), null);
    }

    @ExceptionHandler(value = {Exception.class})
    public ResponseVo<T> exception(Exception e) {
        log.error("Exception 发生异常:{}", e.getMessage(), e);
        return ResponseVo.error(ErrorEnums.FAILURE.getCode(), e.getMessage(), null);
    }

}
